package com.uex.dev.manage.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Preconditions;
import com.uex.dev.manage.admin.dao.ServiceCodeDao;
import com.uex.dev.manage.admin.intercepter.OpenidContext;
import com.uex.dev.manage.admin.po.ProjectPO;
import com.uex.dev.manage.admin.po.ServiceCodePO;
import com.uex.dev.manage.admin.service.IProjectService;
import com.uex.dev.manage.admin.service.IServiceCodeService;
import com.uex.dev.manage.admin.vo.wx.OpenidInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wangchao
 * @since 2024-02-28
 */
@Service
public class ServiceCodeServiceImpl extends ServiceImpl<ServiceCodeDao, ServiceCodePO> implements IServiceCodeService {

    @Resource
    private IProjectService projectService;

    @Override
    public Integer guestBind(String serviceCode) {
        OpenidInfo openidInfo = OpenidContext.getOpenidLocal();
        String wxid = openidInfo.getOpenid();
        LambdaQueryWrapper<ProjectPO> wrapper = Wrappers.<ProjectPO>lambdaQuery()
                .eq(ProjectPO::getPrjEndService, serviceCode);
        ProjectPO project = projectService.getOne(wrapper);
        Preconditions.checkArgument(ObjectUtils.isNotNull(project), "服务码错误");
        LambdaQueryWrapper<ServiceCodePO> wrapperByWxid = Wrappers.<ServiceCodePO>lambdaQuery()
                .eq(ServiceCodePO::getGuestWxid, wxid);
        Preconditions.checkArgument(Objects.isNull(this.getOne(wrapperByWxid)), "当前用户已绑定");
        ServiceCodePO guestInfo = new ServiceCodePO();
        guestInfo.setGuestWxid(wxid);
        guestInfo.setGuestPrjid(project.getPrjId());
        guestInfo.setGuestBindTime(LocalDateTime.now());
        this.save(guestInfo);
        return project.getPrjId();
    }
}
